package com.zqyl.docmanager.service;

import com.zqyl.docmanager.entity.UploadFile;
import com.zqyl.docmanager.repository.UploadFileRepository;
import com.zqyl.docmanager.vo.UploadFileVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UploadFileService {

    @Autowired
    private UploadFileRepository uploadFileRepository;

    @Autowired
    private HtmlConverterService htmlConverterService;

    private final Path uploadPath = Paths.get("D:", "uploads");

    public UploadFileService() {
        try {
            Files.createDirectories(uploadPath);
        } catch (IOException e) {
            log.error("Could not create upload directory!", e);
            throw new RuntimeException("Could not create upload directory!", e);
        }
    }

    public UploadFile uploadFile(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String format = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        String uniqueFilename = UUID.randomUUID().toString() + "." + format;
        String filePath = uploadPath + File.separator + uniqueFilename;

        // Save file to local storage
        File dest = new File(filePath);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        file.transferTo(dest);

        // Convert file to HTML if it's a supported format
        String htmlContent = null;
        if (format.equalsIgnoreCase("docx") || format.equalsIgnoreCase("pdf")) {
            htmlContent = htmlConverterService.convertToHtml(filePath);
        }

        // Create upload file record
        UploadFile uploadFile = new UploadFile();
        uploadFile.setFileName(originalFilename);
        uploadFile.setFilePath(filePath);
        uploadFile.setFileSize(file.getSize());
        uploadFile.setFormat(format);
        uploadFile.setHtmlContent(htmlContent);
        uploadFile.setStatus("待解析");
        uploadFile.setIsDeleted(false);

        return uploadFileRepository.save(uploadFile);
    }

    public List<UploadFile> getAllFiles() {
        return uploadFileRepository.findAllActive();
    }

    public List<UploadFile> searchFiles(String format, String fileName) {
        if (StringUtils.hasText(format) && StringUtils.hasText(fileName)) {
            // 如果同时指定了格式和文件名，需要自定义查询方法
            return uploadFileRepository.findByFormatAndFileNameContaining(format, fileName);
        } else if (StringUtils.hasText(format)) {
            return uploadFileRepository.findByFormat(format);
        } else if (StringUtils.hasText(fileName)) {
            return uploadFileRepository.findByFileNameContaining(fileName);
        } else {
            return getAllFiles();
        }
    }

    public UploadFile getFile(Long id) {
        return uploadFileRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("File not found"));
    }

    public void deleteFile(Long id) {
        UploadFile file = getFile(id);
        file.setIsDeleted(true);
        uploadFileRepository.save(file);
    }

    public List<String> getAllFormats() {
        return uploadFileRepository.findAllFormats();
    }

    public List<UploadFileVO> queryFiles(String format, String fileName) {
        List<UploadFile> files = searchFiles(format, fileName);
        return files.stream()
                .map(file -> {
                    UploadFileVO vo = new UploadFileVO();
                    vo.setId(file.getId());
                    vo.setFileName(file.getFileName());
                    vo.setFormat(file.getFormat());
                    vo.setUploadTime(file.getCreateTime());
                    vo.setFileSize(file.getFileSize());
                    vo.setDownloadUrl("/api/files/download/" + file.getFilePath());
                    return vo;
                })
                .collect(Collectors.toList());
    }

    /**
     * 根据ID获取文件信息
     */
    public UploadFile getFileById(Long id) {
        return uploadFileRepository.findById(id).orElse(null);
    }

    /**
     * 获取文件内容
     */
    public byte[] getFileContent(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException("文件不存在：" + filePath);
        }
        return Files.readAllBytes(file.toPath());
    }
} 